using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using net_work.Common.Request;
using net_work.Common.Result;
using net_work.Data.DTO.Cou;
using net_work.IService.Cou;

namespace net_work.Controllers.Cou;

[Route("api/[controller]")]
[ApiController]
public class EnrollmentController(ILogger<EnrollmentController> logger, IEnrollmentService enrollmentService) : ControllerBase
{
    /// <summary>
    /// 获取选课列表
    /// </summary>
    /// <param name="request">分页请求实体</param>
    /// <returns>操作结果</returns>
    [HttpPost("list")]
    [Authorize]
    public async Task<IActionResult> ListEnrollments([FromBody] PagedRequest request)
    {
        logger.LogInformation("获取选课列表");
        var result = await enrollmentService.GetEnrollmentsPagedAsync(request);
        return AjaxResult.Success(result);
    }

    /// <summary>
    /// 获取选课信息
    /// </summary>
    /// <param name="enrollmentId">选课ID</param>
    /// <returns>操作结果</returns>
    [HttpGet("get")]
    [Authorize]
    public async Task<IActionResult> GetEnrollmentById([FromQuery]long enrollmentId)
    {
        logger.LogInformation("获取选课信息");
        return await enrollmentService.SelectByIdAsync(enrollmentId) is { } enrollment
            ? AjaxResult.Success(enrollment)
            : AjaxResult.Error();
    }
    
    /// <summary>
    /// 新增选课
    /// </summary>
    /// <param name="enrollmentAddRequest">新增选课实体</param>
    /// <returns>操作结果</returns>
    [HttpPost("add")]
    [Authorize(Roles = "STUDENT")]
    public async Task<IActionResult> AddEnrollment([FromBody] EnrollmentAddRequest enrollmentAddRequest)
    {
        logger.LogInformation("新增选课");
        var enrollmentId = await enrollmentService.InsertEnrollment(enrollmentAddRequest);
        return enrollmentId > 0
            ? AjaxResult.Success(new { enrollmentId })
            : AjaxResult.Error();
    }

    /// <summary>
    /// 修改选课
    /// </summary>
    /// <param name="enrollmentUpdateRequest">修改选课实体</param>
    /// <returns>操作结果</returns>
    [HttpPost("update")]
    [Authorize(Roles = "STUDENT")]
    public async Task<IActionResult> UpdateEnrollment([FromBody] EnrollmentUpdateRequest enrollmentUpdateRequest)
    {
        logger.LogInformation("修改选课");
        return await enrollmentService.UpdateEnrollment(enrollmentUpdateRequest) > 0
            ? AjaxResult.Success()
            : AjaxResult.Error();
    }

    /// <summary>
    /// 删除选课
    /// </summary>
    /// <param name="ids">选课ID</param>
    /// <returns>操作结果</returns>
    [HttpPost("delete")]
    [Authorize(Roles = "STUDENT")]
    public async Task<IActionResult> DeleteEnrollment([FromBody] List<long> ids)
    {
        logger.LogInformation("删除选课");
        return await enrollmentService.DeleteEnrollmentByIds(ids) > 0
            ? AjaxResult.Success()
            : AjaxResult.Error();
    }
}